package com.laiqilin.controller;

import cn.hutool.db.PageResult;
import com.laiqilin.entity.Content;
import com.laiqilin.vo.ContentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

Controller
@RequestMapping("/content")
public class ContentController {
    @Autowired
    private ContentService contentService;

    @Autowired
    private FileService fileService;

    @RequestMapping("/list")
    public R getStudent() {
        return R.ok().data("list",contentService.list());
    }

    @PostMapping("/search/{page}/{pageSize}")
    public R search(@PathVariable("page") Integer page,
                    @PathVariable("pageSize") Integer pageSize,
                    @RequestBody(required = false) ContentVO vo){
        PageResult<Content> pr = contentService.search(page,pageSize,vo);
        return R.ok().data("pr",pr);
    }

    @PostMapping("/add")
    public R add(@RequestBody Content content){
        boolean flag = contentService.add(content);
        return flag ? R.ok().message("添加广告成功!") : R.error().message("添加广告失败!");
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {

        String pic = fileService.uploadFile(file);
        return ResponseEntity.ok(pic);
    }
    @PutMapping("/update")
    public R update(@RequestBody Content content){
        boolean flag = contentService.updateById(content);
        return flag ? R.ok().message("修改学生成功!") : R.error().message("修改学生失败!");
    }

    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable("ids") String ids){
        String[] split = ids.split(",");
        List<String> contentIds = Arrays.asList(split);
        return contentService.removeByIds(contentIds) ? R.ok().message("删除学生成功!") : R.error().message("删除学生失败!");
    }
}
